package com.rj.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rj.core.check.AssertFiledValue;
import com.rj.core.check.AssertorBean;
import com.rj.core.domain.BeanDomain;
import com.rj.core.domain.BeanDomain2;
import com.rj.core.type.BeanType;

import java.util.ArrayList;
import java.util.function.Consumer;

/**
 * 断言处理
 *
 * @author YFX_RANLUBO
 * @date 2024/08/09 22:37
 **/
public class AssertBeanUtils {
    public static final AssertorBean ASSERTOR_BEAN = new AssertorBean(null, null, true);

    /**
     * 检查实体对象
     *
     * @param bean
     * @param label
     * @param <T>
     * @return
     */
    public static <T> AssertorBean<T> bean(T bean, String label) {
        return new AssertorBean(bean, label, true);
    }

    /**
     * 检查值
     *
     * @param value
     * @param <T>
     * @param <V>
     * @param <R>
     * @return
     */
    public static <T, V, R> AssertFiledValue<T, V, R> check(V value, BeanType<V> beanType) {
        AssertFiledValue match = ASSERTOR_BEAN.field(value, beanType.getFiledName(), beanType.getAllowEmpty()).maxLen(beanType.getMaxLength()).match(beanType.getRegex(), "");
        Consumer<V> defCheck = beanType.getDefCheck();
        if (defCheck != null) {
            defCheck.accept(value);
        }
        return match;
    }

    /**
     * 检查值
     *
     * @param value
     * @param label
     * @param allowEmpty
     * @param <T>
     * @param <V>
     * @param <R>
     * @return
     */
    public static <T, V, R> AssertFiledValue<T, V, R> check(V value, String label, boolean allowEmpty) {
        return ASSERTOR_BEAN.field(value, label, allowEmpty);
    }

    /**
     * 抛出异常
     */
    public static void throwException(String message, Object... args) {
        ASSERTOR_BEAN.handlerMessage(message, args);
    }

    /**
     * 根据条件（=false）返回异常
     */
    public static void throwExceptionOfFalse(boolean expression, String message, Object... args) {
        ASSERTOR_BEAN.isTrue(expression == false, message, args);
    }

    /**
     * 根据条件（=true）返回异常
     */
    public static void throwExceptionOfTrue(boolean expression, String message, Object... args) {
        ASSERTOR_BEAN.isTrue(expression, message, args);
    }

    /**
     * validate校验框架执行
     *
     * @param bean
     * @param groups
     */
    public static void validate(Object bean, Class<?>... groups) {
        String message = ValidationUtils.validate(bean, groups);
        if (message != null) {
            throwException(message);
        }
    }

    /**
     * 检查值
     *
     * @param value
     * @param label
     * @param allowEmpty
     * @param maxLen
     * @param <T>
     * @param <V>
     * @param <R>
     * @return
     */
    public static <T, V, R> AssertFiledValue<T, V, R> check(V value, String label, boolean allowEmpty, Integer maxLen) {
        return new AssertorBean(null, null, true).field(value, label, allowEmpty, maxLen);
    }

}
